package com.truckdispatching.activity;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.truckdispatching.R;
import com.truckdispatching.database.NotificationSql;
import com.truckdispatching.entity.Notification;
import com.truckdispatching.http.controller.PushHttpController;
import com.truckdispatching.http.util.OnResponseHandler;

/**
 * 系统通知界面
 * 
 * @author Lee
 * @date 2013-4-30
 */
public class NotificationAcivity extends BaseActivity {

	private LinearLayout mContainer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification_activity);

		mContainer = (LinearLayout) findViewById(R.id.notification_container);
		findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		ArrayList<Notification> notifications = NotificationSql.getInstance().findAll();
		if (notifications != null && notifications.size() > 0) {
			initViewWithNotification(notifications);
		}
		PushHttpController controller = new PushHttpController();
		controller.setOnResponseListener(new OnResponseHandler() {
			@Override
			public void onResponseError(int errorCode, String errorMessage) {
				dismissLoadingDialog();
			}

			@Override
			public void onResponse(Object response) {
				ArrayList<Notification> notifications = (ArrayList<Notification>) response;
				initViewWithNotification(notifications);
				dismissLoadingDialog();
			}
		});
		controller.sendRequest(0);
		showLoadingDialog();
	}

	private void initViewWithNotification(ArrayList<Notification> notifications) {
		if (notifications != null && notifications.size() > 0) {
			for (Notification notification : notifications) {
				View item = getLayoutInflater().inflate(R.layout.notification_item_layout, null);
				TextView time = (TextView) item.findViewById(R.id.time);
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
				Date date = new Date(notification.time);
				time.setText(format.format(date));
				TextView content = (TextView) item.findViewById(R.id.content);
				content.setText(notification.content);
				mContainer.addView(item);
			}
		}else{
			showToast("暂时没有新通知");
		}
	}
}
